<?php

use think\facade\Env;

/**
 * @desc 公共api返回方法
 * @param $code
 * @param $msg
 * @param $data
 * @param $httpStatus
 * @return \think\response\Json
 * @author zhaozhiwei
 * @time 2023/12/19-14:30
 */
function show($code = 200, $msg = "", $data = [], $httpStatus = 200)
{
    //如果消息提示为空，并且业务状态码定义了，那么就显示默认定义的消息提示
    if (empty($msg) && !empty(config("status") [$code])) {
        $msg = config("status") [$code];
    }

    $result = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    return json($result, $httpStatus);
}

/**
 * @desc md5登录密码加密
 * @author zhaozhiwei
 * @time 2021/6/29  11:15
 */
function encryptionMd5($password)
{
    $first_salt = Env::get('ENCRYPTION_PASSWORD_FIRST_SALT');
    $second_salt = Env::get('ENCRYPTION_PASSWORD_FIRST_SALT');
    return md5(md5(md5($password) . $first_salt) . $second_salt);
}

/**
 * @desc 二维数组转树状结构
 * @param $array
 * @param $id
 * @param $pid
 * @return array
 * @author zhaozhiwei
 * @time 2023/12/19-14:33
 */
function listToTree($array, $id, $pid)
{
    //第一步 构造数据
    $items = array();
    foreach ($array as $value) {
        $items[$value[$id]] = $value;
    }
    //第二步 遍历数据 生成树状结构
    $tree = array();
    foreach ($items as $key => $value) {
        if (isset($items[$value[$pid]])) {
            $items[$value[$pid]]['children'][] = &$items[$key];
        } else {
            if (!isset($items[$key]['children'])) {
                $items[$key]['children'] = [];
            }
            $tree[] = &$items[$key];
        }
    }
    unset($item);
    return $tree;
}

/**
 * @desc 二位数组按某一列分组方法
 * @param $arr
 * @param $key
 * @return array
 * @author zhaozhiwei
 * @time 2023/12/19-14:34
 */
function array_group_by($arr, $key)
{
    $grouped = [];
    foreach ($arr as $value) {
        $grouped[$value[$key]][] = $value;
    }
    if (func_num_args() > 2) {
        $args = func_get_args();
        foreach ($grouped as $key => $value) {
            $params = array_merge([$value], array_slice($args, 2, func_num_args()));
            $grouped[$key] = call_user_func_array('array_group_by', $params);
        }
    }
    return $grouped;
}

/**
 * @desc ping ip/域名方法
 * @param $address
 * @return bool
 * @author zhaozhiwei
 * @time 2023/12/25-11:31
 */
function pingAddress($address) {
    $outcome='';
    $status=false;
    if (strcasecmp(PHP_OS, 'WINNT') === 0) {
        // Windows 服务器下
        exec("ping -n 1 {$address}", $outcome, $status);
    } elseif (strcasecmp(PHP_OS, 'Linux') === 0) {
        // Linux 服务器下
        exec("ping -c 1 {$address}", $outcome, $status);
    }

    if (0 == $status) {
        $status = true;
    }
    return $status;
}

